package org.mat.ipaas.ucenter.service.modules.system.controller;


import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.config.TenantContext;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.constant.SymbolConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.*;
import org.mat.ipaas.ucenter.biz.config.mybatis.MybatisPlusSaasConfig;
import org.mat.ipaas.ucenter.biz.modules.base.service.BaseCommonService;
import org.mat.ipaas.ucenter.biz.modules.system.entity.*;
import org.mat.ipaas.ucenter.biz.modules.system.model.DepartIdModel;
import org.mat.ipaas.ucenter.biz.modules.system.model.SysUserSysDepartModel;
import org.mat.ipaas.ucenter.biz.modules.system.service.*;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysDepartUsersVO;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysUserRoleVO;
import org.mat.ipaas.ucenter.biz.modules.system.vo.UserAvatar;
import org.mat.ipaas.ucenter.biz.modules.system.vo.lowapp.DepartAndUserInfo;
import org.mat.ipaas.ucenter.biz.modules.system.vo.lowapp.DepartInfo;
import org.mat.ipaas.ucenter.biz.modules.system.vo.lowapp.UpdateDepartInfo;
import org.mat.ipaas.ucenter.service.api.system.SysUserRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysUserAgentDTO;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysUserDTO;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysUserDepartDTO;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysUserRoleDTO;
import org.mat.ipaas.ucenter.service.dto.system.model.DepartIdModelDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.SysDepartUsersVODTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.SysUserRoleVODTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.UserAvatarDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.lowapp.DepartAndUserInfoDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.lowapp.DepartInfoDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.lowapp.UpdateDepartInfoDTO;
import org.mat.ipaas.ucenter.service.modules.JwtUtils;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.modules.TokenUtils;
import org.mat.ipaas.ucenter.service.modules.aop.PermissionData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController implements SysUserRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private ISysDepartRoleUserService departRoleUserService;

    @Autowired
    private ISysDepartRoleService departRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${mat.path.upload}")
    private String upLoadPath;

    @Autowired
    private BaseCommonService baseCommonService;

    @Autowired
    private ISysUserAgentService sysUserAgentService;

    @Autowired
    private ISysPositionService sysPositionService;

    @Autowired
    private ISysUserTenantService userTenantService;

    /**
     * 获取租户下用户数据（支持租户隔离）
     *
     * @param sysUserDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PermissionData(pageComponent = "system/UserList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MatApiResponse<?> queryPageList(@SpringQueryMap SysUserDTO sysUserDTO,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        SysUser user = toSysUser(sysUserDTO);

        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            String tenantId = oConvertUtils.getString(TenantContext.getTenant(), "0");
            //update-begin---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
            List<String> userIds = userTenantService.getUserIdsByTenantId(Integer.valueOf(tenantId));
            if (oConvertUtils.listIsNotEmpty(userIds)) {
                queryWrapper.in("id", userIds);
            } else {
                queryWrapper.eq("id", "通过租户查询不到任何用户");
            }
            //update-end---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
        }
        //------------------------------------------------------------------------------------------------
        return sysUserService.queryPageList(req, queryWrapper, pageSize, pageNo);
    }

    /**
     * 获取系统用户数据（查询全部用户，不做租户隔离）
     *
     * @param sysUserDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@RequiresPermissions("system:user:listAll")
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public MatApiResponse<?> queryAllPageList(@SpringQueryMap SysUserDTO sysUserDTO,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        SysUser user = toSysUser(sysUserDTO);
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        return sysUserService.queryPageList(req, queryWrapper, pageSize, pageNo);
    }

    //@RequiresPermissions("system:user:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public MatApiResponse<SysUserDTO> add(@RequestBody JSONObject jsonObject) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        String selectedRoles = jsonObject.getString("selectedroles");
        String selectedDeparts = jsonObject.getString("selecteddeparts");
        try {
            SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
            user.setCreateTime(new Date());//设置创建时间
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            //用户表字段org_code不能在这里设置他的值
            user.setOrgCode(null);
            // 保存用户走一个service 保证事务
            //获取租户ids
            String relTenantIds = jsonObject.getString("relTenantIds");
            sysUserService.saveUser(user, selectedRoles, selectedDeparts, relTenantIds);
            baseCommonService.addLog("添加用户，username： " + user.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    //@RequiresPermissions("system:user:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysUserDTO> edit(@RequestBody JSONObject jsonObject) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        try {
            SysUser sysUser = sysUserService.getById(jsonObject.getString("id"));
            baseCommonService.addLog("编辑用户，username： " + sysUser.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            if (sysUser == null) {
                matApiResponse.fail("未找到对应实体");
            } else {
                SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
                user.setUpdateTime(new Date());
                //String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), sysUser.getSalt());
                user.setPassword(sysUser.getPassword());
                String roles = jsonObject.getString("selectedroles");
                String departs = jsonObject.getString("selecteddeparts");
                if (oConvertUtils.isEmpty(departs)) {
                    //vue3.0前端只传递了departIds
                    departs = user.getDepartIds();
                }
                //用户表字段org_code不能在这里设置他的值
                user.setOrgCode(null);
                // 修改用户走一个service 保证事务
                //获取租户ids
                String relTenantIds = jsonObject.getString("relTenantIds");
                sysUserService.editUser(user, roles, departs, relTenantIds);
                matApiResponse.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 删除用户
     */
    //@RequiresPermissions("system:user:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public MatApiResponse<?> delete(@RequestParam(name = "id", required = true) String id) {
        baseCommonService.addLog("删除用户，id： " + id, CommonConstant.LOG_TYPE_2, 3);
        this.sysUserService.deleteUser(id);
        return MatApiResponse.success("删除用户成功");
    }

    /**
     * 批量删除用户
     */
    //@RequiresPermissions("system:user:deleteBatch")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public MatApiResponse<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        baseCommonService.addLog("批量删除用户， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        this.sysUserService.deleteBatchUsers(ids);
        return MatApiResponse.success("批量删除用户成功");
    }

    /**
     * 冻结&解冻用户
     *
     * @param jsonObject
     * @return
     */
    //@RequiresPermissions("system:user:frozenBatch")
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public MatApiResponse<SysUserDTO> frozenBatch(@RequestBody JSONObject jsonObject) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("status");
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    this.sysUserService.update(new SysUser().setStatus(Integer.parseInt(status)),
                            new UpdateWrapper<SysUser>().lambda().eq(SysUser::getId, id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败" + e.getMessage());
        }
        matApiResponse.success("操作成功!");
        return matApiResponse;

    }

    //@RequiresPermissions("system:user:queryById")
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public MatApiResponse<SysUserDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysUserDTO(sysUser));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    //@RequiresPermissions("system:user:queryUserRole")
    @RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
    public MatApiResponse<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        MatApiResponse<List<String>> matApiResponse = new MatApiResponse<>();
        List<String> list = new ArrayList<String>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
        if (userRole == null || userRole.size() <= 0) {
            matApiResponse.fail("未找到用户相关角色信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                list.add(sysUserRole.getRoleId());
            }
            matApiResponse.setSuccess(true);
            matApiResponse.setData(list);
        }
        return matApiResponse;
    }


    /**
     * 校验用户账号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUserDTO
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public MatApiResponse<Boolean> checkOnlyUser(SysUserDTO sysUserDTO) {
        MatApiResponse<Boolean> matApiResponse = new MatApiResponse<>();
        SysUser sysUser = toSysUser(sysUserDTO);

        //如果此参数为false则程序发生异常
        matApiResponse.setData(true);
        try {
            //通过传入信息查询新的用户信息
            sysUser.setPassword(null);
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>(sysUser));
            if (user != null) {
                matApiResponse.setSuccess(false);
                matApiResponse.setMessage("用户账号已存在");
                return matApiResponse;
            }

        } catch (Exception e) {
            matApiResponse.setSuccess(false);
            matApiResponse.setMessage(e.getMessage());
            return matApiResponse;
        }
        matApiResponse.setSuccess(true);
        return matApiResponse;
    }

    /**
     * 修改密码
     */
    //@RequiresPermissions("system:user:changepwd")
    @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
    public MatApiResponse<?> changePassword(@RequestBody SysUserDTO sysUserDTO) {
        SysUser sysUser = toSysUser(sysUserDTO);

        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
        if (u == null) {
            return MatApiResponse.fail("用户不存在！");
        }
        sysUser.setId(u.getId());
        //update-begin---author:wangshuai ---date:20220316  for：[VUEN-234]修改密码添加敏感日志------------
        LoginUserDTO loginUser = sessionService.getLoginUser();
        baseCommonService.addLog("修改用户 " + sysUser.getUsername() + " 的密码，操作人： " + loginUser.getUsername(), CommonConstant.LOG_TYPE_2, 2);
        //update-end---author:wangshuai ---date:20220316  for：[VUEN-234]修改密码添加敏感日志------------
        return sysUserService.changePassword(sysUser);
    }

    /**
     * 查询指定用户和部门关联的数据
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
    public MatApiResponse<List<DepartIdModelDTO>> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
        MatApiResponse<List<DepartIdModelDTO>> matApiResponse = new MatApiResponse<>();
        try {
            List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
            if (depIdModelList != null && depIdModelList.size() > 0) {
                matApiResponse.setSuccess(true);
                matApiResponse.setMessage("查找成功");
                matApiResponse.setData(toDepartIdModelDTOList(depIdModelList));
            } else {
                matApiResponse.setSuccess(false);
                matApiResponse.setMessage("查找失败");
            }
            return matApiResponse;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.setSuccess(false);
            matApiResponse.setMessage("查找过程中出现了异常: " + e.getMessage());
            return matApiResponse;
        }

    }

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public MatApiResponse<String> generateUserId() {
        MatApiResponse<String> matApiResponse = new MatApiResponse<>();
        System.out.println("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        matApiResponse.setSuccess(true);
        matApiResponse.setData(userId);
        return matApiResponse;
    }

    /**
     * 根据部门id查询用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryUserByDepId", method = RequestMethod.GET)
    public MatApiResponse<List<SysUserDTO>> queryUserByDepId(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "realname", required = false) String realname) {
        MatApiResponse<List<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        //List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
        SysDepart sysDepart = sysDepartService.getById(id);
        List<SysUser> userList = sysUserDepartService.queryUserByDepCode(sysDepart.getOrgCode(), realname);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = userList.stream().map(SysUser::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            userList.forEach(item -> {
                //TODO 临时借用这个字段用于页面展示
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }

        try {
            matApiResponse.setSuccess(true);
            matApiResponse.setData(toSysUserDTOList(userList));
            return matApiResponse;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
    }

    /**
     * 用户选择组件 专用  根据用户账号或部门分页查询
     *
     * @param departId
     * @param username
     * @return
     */
    @RequestMapping(value = "/queryUserComponentData", method = RequestMethod.GET)
    public MatApiResponse<IPage<SysUserDTO>> queryUserComponentData(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "departId", required = false) String departId,
            @RequestParam(name = "realname", required = false) String realname,
            @RequestParam(name = "username", required = false) String username,
            @RequestParam(name = "id", required = false) String id) {
        //update-begin-author:taoyan date:2022-7-14 for: VUEN-1702【禁止问题】sql注入漏洞
        String[] arr = new String[]{departId, realname, username, id};
        SqlInjectionUtil.filterContent(arr, SymbolConstant.SINGLE_QUOTATION_MARK);
        //update-end-author:taoyan date:2022-7-14 for: VUEN-1702【禁止问题】sql注入漏洞
        IPage<SysUser> pageList = sysUserDepartService.queryDepartUserPageList(departId, username, realname, pageSize, pageNo, id);
        return MatApiResponse.success(toSysUserDTOPage(pageList));
    }

    /**
     * 导出excel
     *
     * @param sysUserDTO
     */
    //@RequiresPermissions("system:user:export")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysUserDTO sysUserDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysUser sysUser = toSysUser(sysUserDTO);

        // Step.1 组装查询条件
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<SysUser> pageList = sysUserService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
        LoginUserDTO user = sessionService.getLoginUser();
        ExportParams exportParams = new ExportParams("用户列表数据", "导出人:" + user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    //@RequiresPermissions("system:user:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse<?> importExcel() throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUser> listSysUsers = ExcelImportUtil.importExcel(file.getInputStream(), SysUser.class, params);
                for (int i = 0; i < listSysUsers.size(); i++) {
                    SysUser sysUserExcel = listSysUsers.get(i);
                    if (StringUtils.isBlank(sysUserExcel.getPassword())) {
                        // 密码默认为 “123456”
                        sysUserExcel.setPassword("123456");
                    }
                    // 密码加密加盐
                    String salt = oConvertUtils.randomGen(8);
                    sysUserExcel.setSalt(salt);
                    String passwordEncode = PasswordUtil.encrypt(sysUserExcel.getUsername(), sysUserExcel.getPassword(), salt);
                    sysUserExcel.setPassword(passwordEncode);
                    try {
                        sysUserService.save(sysUserExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage().toLowerCase();
                        int lineNumber = i + 1;
                        // 通过索引名判断出错信息
                        if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME)) {
                            errorMessage.add("第 " + lineNumber + " 行：用户名已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_WORK_NO)) {
                            errorMessage.add("第 " + lineNumber + " 行：工号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_PHONE)) {
                            errorMessage.add("第 " + lineNumber + " 行：手机号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_EMAIL)) {
                            errorMessage.add("第 " + lineNumber + " 行：电子邮件已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER)) {
                            errorMessage.add("第 " + lineNumber + " 行：违反表唯一性约束。");
                        } else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 批量将部门和用户信息建立关联关系
                    String departIds = sysUserExcel.getDepartIds();
                    if (StringUtils.isNotBlank(departIds)) {
                        String userId = sysUserExcel.getId();
                        String[] departIdArray = departIds.split(",");
                        List<SysUserDepart> userDepartList = new ArrayList<>(departIdArray.length);
                        for (String departId : departIdArray) {
                            userDepartList.add(new SysUserDepart(userId, departId));
                        }
                        sysUserDepartService.saveBatch(userDepartList);
                    }

                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }


    /**
     * @param userIds
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public MatApiResponse<List<SysUserDTO>> queryByIds(@RequestParam String userIds) {
        MatApiResponse<List<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        String[] userId = userIds.split(",");
        List<String> idList = Arrays.asList(userId);
        List<SysUser> userRole = sysUserService.listByIds(idList);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserDTOList(userRole));
        return matApiResponse;
    }


    /**
     * @param userNames
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByNames", method = RequestMethod.GET)
    public MatApiResponse<List<SysUserDTO>> queryByNames(@RequestParam String userNames) {
        MatApiResponse<List<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        String[] names = userNames.split(",");
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().in(true, SysUser::getUsername, names);
        List<SysUser> userRole = sysUserService.list(queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserDTOList(userRole));
        return matApiResponse;
    }

    /**
     * 首页用户重置密码
     */
    //@RequiresPermissions("system:user:updatepwd")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    public MatApiResponse<?> updatePassword(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String oldpassword = json.getString("oldpassword");
        String password = json.getString("password");
        String confirmpassword = json.getString("confirmpassword");
        LoginUserDTO sysUser = sessionService.getLoginUser();
        if (!sysUser.getUsername().equals(username)) {
            return MatApiResponse.fail("只允许修改自己的密码！");
        }
        SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if (user == null) {
            return MatApiResponse.fail("用户不存在！");
        }
        //update-begin---author:wangshuai ---date:20220316  for：[VUEN-234]修改密码添加敏感日志------------
        LoginUserDTO loginUser = sessionService.getLoginUser();
        baseCommonService.addLog("修改密码，username： " + loginUser.getUsername(), CommonConstant.LOG_TYPE_2, 2);
        //update-end---author:wangshuai ---date:20220316  for：[VUEN-234]修改密码添加敏感日志------------
        return sysUserService.resetPassword(username, oldpassword, password, confirmpassword);
    }

    @RequestMapping(value = "/userRoleList", method = RequestMethod.GET)
    public MatApiResponse<Page<SysUserDTO>> userRoleList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        MatApiResponse<Page<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String roleId = req.getParameter("roleId");
        String username = req.getParameter("username");
        IPage<SysUser> pageList = sysUserService.getUserByRoleId(page, roleId, username);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserDTOPage(pageList));
        return matApiResponse;
    }


    /**
     * 给指定角色添加用户
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:user:addUserRole")
    @RequestMapping(value = "/addSysUserRole", method = RequestMethod.POST)
    public MatApiResponse<String> addSysUserRole(@RequestBody SysUserRoleVODTO sysUserRoleVODTO) {
        MatApiResponse<String> matApiResponse = new MatApiResponse<String>();
        SysUserRoleVO sysUserRoleVO = toSysUserRoleVO(sysUserRoleVODTO);

        try {
            String sysRoleId = sysUserRoleVO.getRoleId();
            for (String sysUserId : sysUserRoleVO.getUserIdList()) {
                SysUserRole sysUserRole = new SysUserRole(sysUserId, sysRoleId);
                QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
                queryWrapper.eq("role_id", sysRoleId).eq("user_id", sysUserId);
                SysUserRole one = sysUserRoleService.getOne(queryWrapper);
                if (one == null) {
                    sysUserRoleService.save(sysUserRole);
                }

            }
            matApiResponse.setMessage("添加成功!");
            matApiResponse.setSuccess(true);
            return matApiResponse;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.setSuccess(false);
            matApiResponse.setMessage("出错了: " + e.getMessage());
            return matApiResponse;
        }
    }

    /**
     * 删除指定角色的用户关系
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:user:deleteRole")
    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
    public MatApiResponse<SysUserRoleDTO> deleteUserRole(@RequestParam(name = "roleId") String roleId,
                                                         @RequestParam(name = "userId", required = true) String userId
    ) {
        MatApiResponse<SysUserRoleDTO> matApiResponse = new MatApiResponse<>();
        try {
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).eq("user_id", userId);
            sysUserRoleService.remove(queryWrapper);
            matApiResponse.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("删除失败！");
        }
        return matApiResponse;
    }

    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:user:deleteRoleBatch")
    @RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.DELETE)
    public MatApiResponse<SysUserRoleDTO> deleteUserRoleBatch(
            @RequestParam(name = "roleId") String roleId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        MatApiResponse<SysUserRoleDTO> matApiResponse = new MatApiResponse<>();
        try {
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).in("user_id", Arrays.asList(userIds.split(",")));
            sysUserRoleService.remove(queryWrapper);
            matApiResponse.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("删除失败！");
        }
        return matApiResponse;
    }

    /**
     * 部门用户列表
     */
    @RequestMapping(value = "/departUserList", method = RequestMethod.GET)
    public MatApiResponse<Page<SysUserDTO>> departUserList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        MatApiResponse<Page<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String depId = req.getParameter("depId");
        String username = req.getParameter("username");
        //根据部门ID查询,当前和下级所有的部门IDS
        List<String> subDepids = new ArrayList<>();
        //部门id为空时，查询我的部门下所有用户
        if (oConvertUtils.isEmpty(depId)) {
            LoginUserDTO user = sessionService.getLoginUser();
            int userIdentity = user.getUserIdentity() != null ? user.getUserIdentity() : CommonConstant.USER_IDENTITY_1;
            if (oConvertUtils.isNotEmpty(userIdentity) && userIdentity == CommonConstant.USER_IDENTITY_2) {
                subDepids = sysDepartService.getMySubDepIdsByDepId(user.getDepartIds());
            }
        } else {
            subDepids = sysDepartService.getSubDepIdsByDepId(depId);
        }
        if (subDepids != null && subDepids.size() > 0) {
            IPage<SysUser> pageList = sysUserService.getUserByDepIds(page, subDepids, username);
            //批量查询用户的所属部门
            //step.1 先拿到全部的 useids
            //step.2 通过 useids，一次性查询用户的所属部门名字
            List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
            if (userIds != null && userIds.size() > 0) {
                Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
                pageList.getRecords().forEach(item -> {
                    //批量查询用户的所属部门
                    item.setOrgCode(useDepNames.get(item.getId()));
                });
            }
            //update-begin---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
            //设置租户id
            page.setRecords(userTenantService.setUserTenantIds(page.getRecords()));
            //update-end---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
            matApiResponse.setSuccess(true);
            matApiResponse.setData(toSysUserDTOPage(pageList));
        } else {
            matApiResponse.setSuccess(true);
            matApiResponse.setData(null);
        }
        return matApiResponse;
    }


    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 若某个用户包含多个部门，则会显示多条记录，可自行处理成单条记录
     */
    @GetMapping("/queryByOrgCode")
    public MatApiResponse<?> queryByDepartId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode") String orgCode,
            @SpringQueryMap SysUserDTO sysUserDTO
    ) {
        SysUser sysUser = toSysUser(sysUserDTO);
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, sysUser, new Page(pageNo, pageSize));
        return MatApiResponse.success(pageList);
    }

    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 针对通讯录模块做的接口，将多个部门的用户合并成一条记录，并转成对前端友好的格式
     */
    @GetMapping("/queryByOrgCodeForAddressList")
    public MatApiResponse<?> queryByOrgCodeForAddressList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode", required = false) String orgCode,
            @SpringQueryMap SysUserDTO sysUserDTO
    ) {
        SysUser userParams = toSysUser(sysUserDTO);

        IPage page = new Page(pageNo, pageSize);
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, page);
        List<SysUserSysDepartModel> list = pageList.getRecords();

        // 记录所有出现过的 user, key = userId
        Map<String, JSONObject> hasUser = new HashMap<>(list.size());

        JSONArray resultJson = new JSONArray(list.size());

        for (SysUserSysDepartModel item : list) {
            String userId = item.getId();
            // userId
            JSONObject getModel = hasUser.get(userId);
            // 之前已存在过该用户，直接合并数据
            if (getModel != null) {
                String departName = getModel.get("departName").toString();
                getModel.put("departName", (departName + " | " + item.getDepartName()));
            } else {
                // 将用户对象转换为json格式，并将部门信息合并到 json 中
                JSONObject json = JSON.parseObject(JSON.toJSONString(item));
                json.remove("id");
                json.put("userId", userId);
                json.put("departId", item.getDepartId());
                json.put("departName", item.getDepartName());
//                json.put("avatar", item.getSysUser().getAvatar());
                resultJson.add(json);
                hasUser.put(userId, json);
            }
        }

        IPage<JSONObject> result = new Page<>(pageNo, pageSize, pageList.getTotal());
        result.setRecords(resultJson.toJavaList(JSONObject.class));
        return MatApiResponse.success(result);
    }

    /**
     * 给指定部门添加对应的用户
     */
    //@RequiresPermissions("system:user:editDepartWithUser")
    @RequestMapping(value = "/editSysDepartWithUser", method = RequestMethod.POST)
    public MatApiResponse<String> editSysDepartWithUser(@RequestBody SysDepartUsersVODTO sysDepartUsersVODTO) {
        MatApiResponse<String> matApiResponse = new MatApiResponse<String>();
        SysDepartUsersVO sysDepartUsersVO = toSysDepartUsersVO(sysDepartUsersVODTO);

        try {
            String sysDepId = sysDepartUsersVO.getDepId();
            for (String sysUserId : sysDepartUsersVO.getUserIdList()) {
                SysUserDepart sysUserDepart = new SysUserDepart(null, sysUserId, sysDepId);
                QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
                queryWrapper.eq("dep_id", sysDepId).eq("user_id", sysUserId);
                SysUserDepart one = sysUserDepartService.getOne(queryWrapper);
                if (one == null) {
                    sysUserDepartService.save(sysUserDepart);
                }
            }
            matApiResponse.setMessage("添加成功!");
            matApiResponse.setSuccess(true);
            return matApiResponse;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.setSuccess(false);
            matApiResponse.setMessage("出错了: " + e.getMessage());
            return matApiResponse;
        }
    }


    /**
     * 删除指定机构的用户关系
     */
    //@RequiresPermissions("system:user:deleteUserInDepart")
    @RequestMapping(value = "/deleteUserInDepart", method = RequestMethod.DELETE)
    public MatApiResponse<SysUserDepartDTO> deleteUserInDepart(@RequestParam(name = "depId") String depId,
                                                               @RequestParam(name = "userId", required = true) String userId
    ) {
        MatApiResponse<SysUserDepartDTO> matApiResponse = new MatApiResponse<>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).eq("user_id", userId);
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().eq("depart_id", depId));
                List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                if (roleIds != null && roleIds.size() > 0) {
                    QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
                    query.eq("user_id", userId).in("drole_id", roleIds);
                    departRoleUserService.remove(query);
                }
                matApiResponse.success("删除成功!");
            } else {
                matApiResponse.fail("当前选中部门与用户无关联关系!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("删除失败！");
        }
        return matApiResponse;
    }

    /**
     * 批量删除指定机构的用户关系
     */
    //@RequiresPermissions("system:user:deleteUserInDepartBatch")
    @RequestMapping(value = "/deleteUserInDepartBatch", method = RequestMethod.DELETE)
    public MatApiResponse<SysUserDepartDTO> deleteUserInDepartBatch(
            @RequestParam(name = "depId") String depId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        MatApiResponse<SysUserDepartDTO> matApiResponse = new MatApiResponse<>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).in("user_id", Arrays.asList(userIds.split(",")));
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                departRoleUserService.removeDeptRoleUser(Arrays.asList(userIds.split(",")), depId);
            }
            matApiResponse.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("删除失败！");
        }
        return matApiResponse;
    }

    /**
     * 查询当前用户的所有部门/当前部门编码
     *
     * @return
     */
    @RequestMapping(value = "/getCurrentUserDeparts", method = RequestMethod.GET)
    public MatApiResponse<Map<String, Object>> getCurrentUserDeparts() {
        MatApiResponse<Map<String, Object>> matApiResponse = new MatApiResponse<Map<String, Object>>();
        try {
            LoginUserDTO sysUser = sessionService.getLoginUser();
            List<SysDepart> list = this.sysDepartService.queryUserDeparts(sysUser.getId());
            Map<String, Object> map = new HashMap(5);
            map.put("list", list);
            map.put("orgCode", sysUser.getOrgCode());
            matApiResponse.setSuccess(true);
            matApiResponse.setData(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("查询失败！");
        }
        return matApiResponse;
    }


    /**
     * 用户注册接口
     *
     * @param jsonObject
     * @param sysUserDTO
     * @return
     */
    @PostMapping("/register")
    public MatApiResponse<JSONObject> userRegister(@RequestBody JSONObject jsonObject, @RequestParam("sysUserDTO") SysUserDTO sysUserDTO) {
        MatApiResponse<JSONObject> matApiResponse = new MatApiResponse<JSONObject>();
        SysUser user = toSysUser(sysUserDTO);

        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");

        //update-begin-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
        String redisKey = CommonConstant.PHONE_REDIS_KEY_PRE + phone;
        Object code = redisUtil.get(redisKey);
        //update-end-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906

        String username = jsonObject.getString("username");
        //未设置用户名，则用手机号作为用户名
        if (oConvertUtils.isEmpty(username)) {
            username = phone;
        }
        //未设置密码，则随机生成一个密码
        String password = jsonObject.getString("password");
        if (oConvertUtils.isEmpty(password)) {
            password = RandomUtil.randomString(8);
        }
        String email = jsonObject.getString("email");
        SysUser sysUser1 = sysUserService.getUserByName(username);
        if (sysUser1 != null) {
            matApiResponse.setMessage("用户名已注册");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        SysUser sysUser2 = sysUserService.getUserByPhone(phone);
        if (sysUser2 != null) {
            matApiResponse.setMessage("该手机号已注册");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }

        if (oConvertUtils.isNotEmpty(email)) {
            SysUser sysUser3 = sysUserService.getUserByEmail(email);
            if (sysUser3 != null) {
                matApiResponse.setMessage("邮箱已被注册");
                matApiResponse.setSuccess(false);
                return matApiResponse;
            }
        }
        if (null == code) {
            matApiResponse.setMessage("手机验证码失效，请重新获取");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        if (!smscode.equals(code.toString())) {
            matApiResponse.setMessage("手机验证码错误");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }

        String realname = jsonObject.getString("realname");
        if (oConvertUtils.isEmpty(realname)) {
            realname = username;
        }

        try {
            user.setCreateTime(new Date());// 设置创建时间
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            user.setSalt(salt);
            user.setUsername(username);
            user.setRealname(realname);
            user.setPassword(passwordEncode);
            user.setEmail(email);
            user.setPhone(phone);
            user.setStatus(CommonConstant.USER_UNFREEZE);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            user.setActivitiSync(CommonConstant.ACT_SYNC_0);
            sysUserService.addUserWithRole(user, null);
            matApiResponse.success("注册成功");
        } catch (Exception e) {
            matApiResponse.fail("注册失败");
        }
        return matApiResponse;
    }

//	/**
//	 * 根据用户名或手机号查询用户信息
//	 * @param
//	 * @return
//	 */
//	@GetMapping("/querySysUser")
//	public Result<Map<String, Object>> querySysUser(SysUser sysUser) {
//		String phone = sysUser.getPhone();
//		String username = sysUser.getUsername();
//		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
//		Map<String, Object> map = new HashMap<String, Object>();
//		if (oConvertUtils.isNotEmpty(phone)) {
//			SysUser user = sysUserService.getUserByPhone(phone);
//			if(user!=null) {
//				map.put("username",user.getUsername());
//				map.put("phone",user.getPhone());
//				result.setSuccess(true);
//				result.setResult(map);
//				return result;
//			}
//		}
//		if (oConvertUtils.isNotEmpty(username)) {
//			SysUser user = sysUserService.getUserByName(username);
//			if(user!=null) {
//				map.put("username",user.getUsername());
//				map.put("phone",user.getPhone());
//				result.setSuccess(true);
//				result.setResult(map);
//				return result;
//			}
//		}
//		result.setSuccess(false);
//		result.setMessage("验证失败");
//		return result;
//	}

    /**
     * 用户手机号验证
     */
    @PostMapping("/phoneVerification")
    public MatApiResponse<Map<String, String>> phoneVerification(@RequestBody JSONObject jsonObject) {
        MatApiResponse<Map<String, String>> matApiResponse = new MatApiResponse<Map<String, String>>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        //update-begin-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
        String redisKey = CommonConstant.PHONE_REDIS_KEY_PRE + phone;
        Object code = redisUtil.get(redisKey);
        if (!smscode.equals(code)) {
            matApiResponse.setMessage("手机验证码错误");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        //设置有效时间
        redisUtil.set(redisKey, smscode, 600);
        //update-end-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906

        //新增查询用户名
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getPhone, phone);
        SysUser user = sysUserService.getOne(query);
        Map<String, String> map = new HashMap(5);
        map.put("smscode", smscode);
        if (null == user) {
            //前端根据文字做判断用户是否存在判断，不能修改
            matApiResponse.setMessage("用户信息不存在");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        map.put("username", user.getUsername());
        matApiResponse.setData(map);
        matApiResponse.setSuccess(true);
        return matApiResponse;
    }

    /**
     * 用户更改密码
     */
    @GetMapping("/passwordChange")
    public MatApiResponse<SysUserDTO> passwordChange(@RequestParam(name = "username") String username,
                                                     @RequestParam(name = "password") String password,
                                                     @RequestParam(name = "smscode") String smscode,
                                                     @RequestParam(name = "phone") String phone) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        if (oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(password) || oConvertUtils.isEmpty(smscode) || oConvertUtils.isEmpty(phone)) {
            matApiResponse.setMessage("重置密码失败！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }

        SysUser sysUser = new SysUser();
        //update-begin-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
        String redisKey = CommonConstant.PHONE_REDIS_KEY_PRE + phone;
        Object object = redisUtil.get(redisKey);
        //update-end-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
        if (null == object) {
            matApiResponse.setMessage("短信验证码失效！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        if (!smscode.equals(object.toString())) {
            matApiResponse.setMessage("短信验证码不匹配！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username).eq(SysUser::getPhone, phone));
        if (sysUser == null) {
            matApiResponse.setMessage("未找到用户！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        } else {
            String salt = oConvertUtils.randomGen(8);
            sysUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
            sysUser.setPassword(passwordEncode);
            this.sysUserService.updateById(sysUser);
            //update-begin---author:wangshuai ---date:20220316  for：[VUEN-234]密码重置添加敏感日志------------
            baseCommonService.addLog("重置 " + username + " 的密码，操作人： " + sysUser.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            //update-end---author:wangshuai ---date:20220316  for：[VUEN-234]密码重置添加敏感日志------------
            matApiResponse.setSuccess(true);
            matApiResponse.setMessage("密码重置完成！");
            return matApiResponse;
        }
    }


    /**
     * 根据TOKEN获取用户的部分信息（返回的数据是可供表单设计器使用的数据）
     *
     * @return
     */
    @GetMapping("/getUserSectionInfoByToken")
    public MatApiResponse<?> getUserSectionInfoByToken(@RequestHeader("X-Access-Token") String accessToken,
                                                       @RequestParam(name = "token", required = false) String token) {
        try {
            String username = null;
            // 如果没有传递token，就从header中获取token并获取用户信息
            if (oConvertUtils.isEmpty(token)) {
                username = JwtUtils.getUserNameByToken(accessToken);
            } else {
                username = JwtUtils.getUsername(token);
            }

            log.debug(" ------ 通过令牌获取部分用户信息，当前用户： " + username);

            // 根据用户名查询用户信息
            SysUser sysUser = sysUserService.getUserByName(username);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sysUserId", sysUser.getId());
            map.put("sysUserCode", sysUser.getUsername()); // 当前登录用户登录账号
            map.put("sysUserName", sysUser.getRealname()); // 当前登录用户真实名称
            map.put("sysOrgCode", sysUser.getOrgCode()); // 当前登录用户部门编号

            log.debug(" ------ 通过令牌获取部分用户信息，已获取的用户信息： " + map);

            return MatApiResponse.success(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return MatApiResponse.fail(500, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 【APP端接口】获取用户列表  根据用户名和真实名 模糊匹配
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/appUserList")
    public MatApiResponse<?> appUserList(@RequestParam(name = "keyword", required = false) String keyword,
                                         @RequestParam(name = "username", required = false) String username,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         @RequestParam(name = "syncFlow", required = false) String syncFlow) {
        try {
            //TODO 从查询效率上将不要用mp的封装的page分页查询 建议自己写分页语句
            LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>();
            if (oConvertUtils.isNotEmpty(syncFlow)) {
                query.eq(SysUser::getActivitiSync, CommonConstant.ACT_SYNC_1);
            }
            query.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_0);
            if (oConvertUtils.isNotEmpty(username)) {
                if (username.contains(",")) {
                    query.in(SysUser::getUsername, username.split(","));
                } else {
                    query.eq(SysUser::getUsername, username);
                }
            } else {
                query.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
            }
            Page<SysUser> page = new Page<>(pageNo, pageSize);
            IPage<SysUser> res = this.sysUserService.page(page, query);
            return MatApiResponse.success(res);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return MatApiResponse.fail(500, "查询失败:" + e.getMessage());
        }

    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBin")
    public MatApiResponse getRecycleBin() {
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted();
        if (logicDeletedUserList.size() > 0) {
            // 批量查询用户的所属部门
            // step.1 先拿到全部的 userIds
            List<String> userIds = logicDeletedUserList.stream().map(SysUser::getId).collect(Collectors.toList());
            // step.2 通过 userIds，一次性查询用户的所属部门名字
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            logicDeletedUserList.forEach(item -> item.setOrgCode(useDepNames.get(item.getId())));
        }
        return MatApiResponse.success(logicDeletedUserList);
    }

    /**
     * 还原被逻辑删除的用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
    public MatApiResponse putRecycleBin(@RequestHeader("X-Access-Token") String accessToken,
                                        @RequestBody JSONObject jsonObject) {
        String userIds = jsonObject.getString("userIds");
        if (StringUtils.isNotBlank(userIds)) {
            SysUser updateUser = new SysUser();
            updateUser.setUpdateBy(JwtUtils.getUserNameByToken(accessToken));
            updateUser.setUpdateTime(new Date());
            sysUserService.revertLogicDeleted(Arrays.asList(userIds.split(",")), updateUser);
        }
        return MatApiResponse.success("还原成功");
    }

    /**
     * 彻底删除用户
     *
     * @param userIds 被删除的用户ID，多个id用半角逗号分割
     * @return
     */
    //@RequiresPermissions("system:user:deleteRecycleBin")
    @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE)
    public MatApiResponse deleteRecycleBin(@RequestParam("userIds") String userIds) {
        if (StringUtils.isNotBlank(userIds)) {
            sysUserService.removeLogicDeleted(Arrays.asList(userIds.split(",")));
        }
        return MatApiResponse.success("删除成功");
    }


    /**
     * 移动端修改用户信息
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/appEdit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysUserDTO> appEdit(@RequestHeader("X-Access-Token") String accessToken,
                                              @RequestBody JSONObject jsonObject) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        try {
            String username = JwtUtils.getUserNameByToken(accessToken);
            SysUser sysUser = sysUserService.getUserByName(username);
            baseCommonService.addLog("移动端编辑用户，id： " + jsonObject.getString("id"), CommonConstant.LOG_TYPE_2, 2);
            String realname = jsonObject.getString("realname");
            String avatar = jsonObject.getString("avatar");
            String sex = jsonObject.getString("sex");
            String phone = jsonObject.getString("phone");
            String email = jsonObject.getString("email");
            Date birthday = jsonObject.getDate("birthday");
            SysUser userPhone = sysUserService.getUserByPhone(phone);
            if (sysUser == null) {
                matApiResponse.fail("未找到对应用户!");
            } else {
                if (userPhone != null) {
                    String userPhonename = userPhone.getUsername();
                    if (!userPhonename.equals(username)) {
                        matApiResponse.fail("手机号已存在!");
                        return matApiResponse;
                    }
                }
                if (StringUtils.isNotBlank(realname)) {
                    sysUser.setRealname(realname);
                }
                if (StringUtils.isNotBlank(avatar)) {
                    sysUser.setAvatar(avatar);
                }
                if (StringUtils.isNotBlank(sex)) {
                    sysUser.setSex(Integer.parseInt(sex));
                }
                if (StringUtils.isNotBlank(phone)) {
                    sysUser.setPhone(phone);
                }
                if (StringUtils.isNotBlank(email)) {
                    //update-begin---author:wangshuai ---date:20220708  for：[VUEN-1528]积木官网邮箱重复，应该提示准确------------
                    LambdaQueryWrapper<SysUser> emailQuery = new LambdaQueryWrapper<>();
                    emailQuery.eq(SysUser::getEmail, email);
                    long count = sysUserService.count(emailQuery);
                    if (!email.equals(sysUser.getEmail()) && count != 0) {
                        matApiResponse.fail("保存失败，邮箱已存在!");
                        return matApiResponse;
                    }
                    //update-end---author:wangshuai ---date:20220708  for：[VUEN-1528]积木官网邮箱重复，应该提示准确--------------
                    sysUser.setEmail(email);
                }
                if (null != birthday) {
                    sysUser.setBirthday(birthday);
                }
                sysUser.setUpdateTime(new Date());
                sysUserService.updateById(sysUser);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("保存失败!");
        }
        return matApiResponse;
    }

    /**
     * 移动端保存设备信息
     *
     * @param clientId
     * @return
     */
    @RequestMapping(value = "/saveClientId", method = RequestMethod.GET)
    public MatApiResponse<SysUserDTO> saveClientId(@RequestHeader("X-Access-Token") String accessToken,
                                                   @RequestParam("clientId") String clientId) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        try {
            String username = JwtUtils.getUserNameByToken(accessToken);
            SysUser sysUser = sysUserService.getUserByName(username);
            if (sysUser == null) {
                matApiResponse.fail("未找到对应用户!");
            } else {
                sysUser.setClientId(clientId);
                sysUserService.updateById(sysUser);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败!");
        }
        return matApiResponse;
    }

    /**
     * 根据userid获取用户信息和部门员工信息
     *
     * @return Result
     */
    @GetMapping("/queryChildrenByUsername")
    public MatApiResponse queryChildrenByUsername(@RequestParam("userId") String userId) {
        //获取用户信息
        Map<String, Object> map = new HashMap(5);
        SysUser sysUser = sysUserService.getById(userId);
        String username = sysUser.getUsername();
        Integer identity = sysUser.getUserIdentity();
        map.put("sysUser", sysUser);
        if (identity != null && identity == 2) {
            //获取部门用户信息
            String departIds = sysUser.getDepartIds();
            if (StringUtils.isNotBlank(departIds)) {
                List<String> departIdList = Arrays.asList(departIds.split(","));
                List<SysUser> childrenUser = sysUserService.queryByDepIds(departIdList, username);
                map.put("children", childrenUser);
            }
        }
        return MatApiResponse.success(map);
    }

    /**
     * 移动端查询部门用户信息
     *
     * @param departId
     * @return
     */
    @GetMapping("/appQueryByDepartId")
    public MatApiResponse<List<SysUserDTO>> appQueryByDepartId(@RequestParam(name = "departId", required = false) String departId) {
        MatApiResponse<List<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        List<String> list = new ArrayList<String>();
        list.add(departId);
        List<SysUser> childrenUser = sysUserService.queryByDepIds(list, null);
        matApiResponse.setData(toSysUserDTOList(childrenUser));
        return matApiResponse;
    }

    /**
     * 移动端查询用户信息(通过用户名模糊查询)
     *
     * @param keyword
     * @return
     */
    @GetMapping("/appQueryUser")
    public MatApiResponse<List<SysUserDTO>> appQueryUser(@RequestParam(name = "keyword", required = false) String keyword,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        MatApiResponse<List<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne(SysUser::getUsername, "_reserve_user_external");
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
        }
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageList = this.sysUserService.page(page, queryWrapper);
        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.getRecords().forEach(item -> {
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        matApiResponse.setData(toSysUserDTOList(pageList.getRecords()));
        return matApiResponse;
    }

    /**
     * 根据用户名修改手机号[该方法未使用]
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/updateMobile", method = RequestMethod.PUT)
    public MatApiResponse<?> changMobile(@RequestHeader("X-Access-Token") String accessToken,
                                         @RequestBody JSONObject json) {
        String smscode = json.getString("smscode");
        String phone = json.getString("phone");
        MatApiResponse<SysUser> matApiResponse = new MatApiResponse<SysUser>();
        //获取登录用户名
        String username = JwtUtils.getUserNameByToken(accessToken);
        if (oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(smscode) || oConvertUtils.isEmpty(phone)) {
            matApiResponse.setMessage("修改手机号失败！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        //update-begin-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
        String redisKey = CommonConstant.PHONE_REDIS_KEY_PRE + phone;
        Object object = redisUtil.get(redisKey);
        //update-end-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
        if (null == object) {
            matApiResponse.setMessage("短信验证码失效！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        if (!smscode.equals(object.toString())) {
            matApiResponse.setMessage("短信验证码不匹配！");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        SysUser user = sysUserService.getUserByName(username);
        if (user == null) {
            return MatApiResponse.fail("用户不存在！");
        }
        user.setPhone(phone);
        sysUserService.updateById(user);
        return MatApiResponse.success("手机号设置成功!");
    }


    /**
     * 根据对象里面的属性值作in查询 属性可能会变 用户组件用到
     *
     * @param sysUserDTO
     * @return
     */
    @GetMapping("/getMultiUser")
    public List<SysUserDTO> getMultiUser(SysUserDTO sysUserDTO) {
        SysUser sysUser = toSysUser(sysUserDTO);
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, null);
        //update-begin---author:wangshuai ---date:20220104  for：[JTC-297]已冻结用户仍可设置为代理人------------
        queryWrapper.eq("status", Integer.parseInt(CommonConstant.STATUS_1));
        //update-end---author:wangshuai ---date:20220104  for：[JTC-297]已冻结用户仍可设置为代理人------------
        List<SysUser> ls = this.sysUserService.list(queryWrapper);
        for (SysUser user : ls) {
            user.setPassword(null);
            user.setSalt(null);
        }
        return toSysUserDTOList(ls);
    }

    /**
     * 聊天 创建聊天组件专用  根据用户账号、用户姓名、部门id分页查询
     *
     * @param departId 部门id
     * @param keyword  搜索值
     * @return
     */
    @GetMapping(value = "/getUserInformation")
    public MatApiResponse<IPage<SysUserDTO>> getUserInformation(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "departId", required = false) String departId,
            @RequestParam(name = "keyword", required = false) String keyword) {
        //------------------------------------------------------------------------------------------------
        Integer tenantId = null;
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            tenantId = oConvertUtils.getInt(TenantContext.getTenant(), 0);
        }
        //------------------------------------------------------------------------------------------------
        IPage<SysUser> pageList = sysUserDepartService.getUserInformation(tenantId, departId, keyword, pageSize, pageNo);
        return MatApiResponse.success(toSysUserDTOPage(pageList));
    }

    /**
     * 简版流程用户选择组件
     *
     * @param departId 部门id
     * @param roleId   角色id
     * @param keyword  搜索值
     * @return
     */
    @GetMapping(value = "/selectUserList")
    public MatApiResponse<IPage<SysUserDTO>> selectUserList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "departId", required = false) String departId,
            @RequestParam(name = "roleId", required = false) String roleId,
            @RequestParam(name = "keyword", required = false) String keyword) {
        //------------------------------------------------------------------------------------------------
        Integer tenantId = null;
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            String tenantStr = TenantContext.getTenant();
            if (oConvertUtils.isNotEmpty(tenantStr)) {
                tenantId = Integer.parseInt(tenantStr);
            }
        }
        //------------------------------------------------------------------------------------------------
        IPage<SysUser> pageList = sysUserDepartService.getUserInformation(tenantId, departId, roleId, keyword, pageSize, pageNo);
        return MatApiResponse.success(toSysUserDTOPage(pageList));
    }

    /**
     * 用户离职(新增代理人和用户状态变更操作)【低代码应用专用接口】
     *
     * @param sysUserAgentDTO
     * @return
     */
    @PutMapping("/userQuitAgent")
    public MatApiResponse<String> userQuitAgent(@RequestBody SysUserAgentDTO sysUserAgentDTO) {
        SysUserAgent sysUserAgent = toSysUserAgent(sysUserAgentDTO);
        //判断id是否为空
        if (oConvertUtils.isNotEmpty(sysUserAgent.getId())) {
            sysUserAgentService.updateById(sysUserAgent);
        } else {
            sysUserAgentService.save(sysUserAgent);
        }
        sysUserService.userQuit(sysUserAgent.getUserName());
        return MatApiResponse.success("离职成功");
    }


    /**
     * 获取被逻辑删除的用户列表，无分页【低代码应用专用接口】
     *
     * @return List<SysUser>
     */
    @GetMapping("/getQuitList")
    public MatApiResponse<List<SysUserDTO>> getQuitList(HttpServletRequest req) {
        Integer tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(req), 0);
        List<SysUser> quitList = sysUserService.getQuitList(tenantId);
        if (null != quitList && quitList.size() > 0) {
            // 批量查询用户的所属部门
            // step.1 先拿到全部的 userIds
            List<String> userIds = quitList.stream().map(SysUser::getId).collect(Collectors.toList());
            // step.2 通过 userIds，一次性查询用户的所属部门名字
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            quitList.forEach(item -> item.setOrgCode(useDepNames.get(item.getId())));
        }
        return MatApiResponse.success(toSysUserDTOList(quitList));
    }

    /**
     * 更新刪除状态和离职状态【低代码应用专用接口】
     *
     * @param jsonObject
     * @return Result<String>
     */
    @PutMapping("/putCancelQuit")
    public MatApiResponse<String> putCancelQuit(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String userIds = jsonObject.getString("userIds");
        String usernames = jsonObject.getString("usernames");
        Integer tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request), 0);
        //将状态改成未删除
        if (StringUtils.isNotBlank(userIds)) {
            userTenantService.putCancelQuit(Arrays.asList(userIds.split(SymbolConstant.COMMA)), tenantId);
        }
        if (StringUtils.isNotEmpty(usernames)) {
            //根据用户名删除代理人
            LambdaQueryWrapper<SysUserAgent> query = new LambdaQueryWrapper<>();
            query.in(SysUserAgent::getUserName, Arrays.asList(usernames.split(SymbolConstant.COMMA)));
            sysUserAgentService.remove(query);
        }
        return MatApiResponse.success("取消离职成功");
    }

    /**
     * 获取用户信息(vue3用户设置专用)【低代码应用专用接口】
     *
     * @return
     */
    @GetMapping("/login/setting/getUserData")
    public MatApiResponse<SysUserDTO> getUserData(@RequestHeader("X-Access-Token") String accessToken) {
        String username = JwtUtils.getUserNameByToken(accessToken);
        SysUser user = sysUserService.getUserByName(username);
        if (user == null) {
            return MatApiResponse.fail("未找到该用户数据");
        }
        if (oConvertUtils.isNotEmpty(user.getPost())) {
            String post = user.getPost();
            LambdaQueryWrapper<SysPosition> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysPosition::getCode, Arrays.asList(post.split(SymbolConstant.COMMA)));
            queryWrapper.select(SysPosition::getName);
            List<SysPosition> sysPositionList = sysPositionService.list(queryWrapper);
            StringBuilder nameBuilder = new StringBuilder();
            String verticalBar = " | ";
            for (SysPosition sysPosition : sysPositionList) {
                nameBuilder.append(sysPosition.getName()).append(verticalBar);
            }
            String names = nameBuilder.toString();
            if (oConvertUtils.isNotEmpty(names)) {
                names = names.substring(0, names.lastIndexOf(verticalBar));
                user.setPostText(names);
            }
        }
        return MatApiResponse.success(toSysUserDTO(user));
    }

    /**
     * 用户编辑(vue3用户设置专用)【低代码应用专用接口】
     *
     * @param sysUserDTO
     * @return
     */
    @PostMapping("/login/setting/userEdit")
    //@RequiresPermissions("system:user:setting:edit")
    public MatApiResponse<String> userEdit(@RequestHeader("X-Access-Token") String accessToken,
                                           @RequestBody SysUserDTO sysUserDTO) {
        SysUser sysUser = toSysUser(sysUserDTO);
        String username = JwtUtils.getUserNameByToken(accessToken);
        SysUser user = sysUserService.getById(sysUser.getId());
        if (user == null) {
            return MatApiResponse.fail("未找到该用户数据");
        }
        if (!username.equals(user.getUsername())) {
            return MatApiResponse.fail("只能修改自己的数据");
        }
        sysUserService.updateById(sysUser);
        return MatApiResponse.success("更新个人信息成功");
    }

    /**
     * 批量修改 【low-app】
     *
     * @param jsonObject
     * @return
     */
    @PutMapping("/batchEditUsers")
    public MatApiResponse<SysUserDTO> batchEditUsers(@RequestBody JSONObject jsonObject) {
        MatApiResponse<SysUserDTO> matApiResponse = new MatApiResponse<>();
        try {
            sysUserService.batchEditUsers(jsonObject);
            matApiResponse.setSuccess(true);
            matApiResponse.setMessage("操作成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 根据关键词搜索部门和用户【low-app】
     *
     * @param keyword
     * @return
     */
    @GetMapping("/searchByKeyword")
    public MatApiResponse<DepartAndUserInfoDTO> searchByKeyword(@RequestParam(name = "keyword", required = false) String keyword) {
        DepartAndUserInfo info = sysUserService.searchByKeyword(keyword);
        return MatApiResponse.success(toDepartAndUserInfoDTO(info));
    }

    /**
     * 编辑部门前获取部门相关信息 【low-app】
     *
     * @param id
     * @return
     */
    @GetMapping("/getUpdateDepartInfo")
    public MatApiResponse<UpdateDepartInfoDTO> getUpdateDepartInfo(@RequestParam(name = "id", required = false) String id) {
        UpdateDepartInfo info = sysUserService.getUpdateDepartInfo(id);
        return MatApiResponse.success(toUpdateDepartInfoDTO(info));
    }

    /**
     * 编辑部门 【low-app】
     *
     * @param updateDepartInfoDTO
     * @return
     */
    @PutMapping("/doUpdateDepartInfo")
    public MatApiResponse<?> doUpdateDepartInfo(@RequestBody UpdateDepartInfoDTO updateDepartInfoDTO) {
        UpdateDepartInfo updateDepartInfo = toUpdateDepartInfo(updateDepartInfoDTO);
        sysUserService.doUpdateDepartInfo(updateDepartInfo);
        return MatApiResponse.success();
    }

    /**
     * 设置负责人 取消负责人
     *
     * @param json
     * @return
     */
    @PutMapping("/changeDepartChargePerson")
    public MatApiResponse<?> changeDepartChargePerson(@RequestBody JSONObject json) {
        sysUserService.changeDepartChargePerson(json);
        return MatApiResponse.success();
    }

    /**
     * 修改租户下的用户【低代码应用专用接口】
     *
     * @param sysUserDTO
     * @return
     */
    @RequestMapping(value = "/editTenantUser", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<String> editTenantUser(@RequestBody SysUserDTO sysUserDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MatApiResponse<String> matApiResponse = new MatApiResponse<>();
        SysUser sysUser = toSysUser(sysUserDTO);

        String tenantId = TokenUtils.getTenantIdByRequest(request);
        if (oConvertUtils.isEmpty(tenantId)) {
            return matApiResponse.fail("无权修改他人信息！");
        }
        LambdaQueryWrapper<SysUserTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysUserTenant::getTenantId, Integer.valueOf(tenantId));
        query.eq(SysUserTenant::getUserId, sysUser.getId());
        SysUserTenant one = userTenantService.getOne(query);
        if (null == one) {
            return matApiResponse.fail("非当前租户下的用户，不允许修改！");
        }
        String departs = request.getParameter("selecteddeparts");
        String roles = request.getParameter("selectedroles");
        sysUserService.editTenantUser(sysUser, tenantId, departs, roles);
        return MatApiResponse.success("修改成功");
    }


    private SysUser toSysUser(SysUserDTO sysUserDTO) {
        if (sysUserDTO == null) {
            return null;
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(sysUserDTO.getId());
        sysUser.setUsername(sysUserDTO.getUsername());
        sysUser.setRealname(sysUserDTO.getRealname());
        sysUser.setPassword(sysUserDTO.getPassword());
        sysUser.setSalt(sysUserDTO.getSalt());
        sysUser.setAvatar(sysUserDTO.getAvatar());
        sysUser.setBirthday(sysUserDTO.getBirthday());
        sysUser.setSex(sysUserDTO.getSex());
        sysUser.setEmail(sysUserDTO.getEmail());
        sysUser.setPhone(sysUserDTO.getPhone());
        sysUser.setOrgCode(sysUserDTO.getOrgCode());
        sysUser.setLoginTenantId(sysUserDTO.getLoginTenantId());
        sysUser.setOrgCodeTxt(sysUserDTO.getOrgCodeTxt());
        sysUser.setStatus(sysUserDTO.getStatus());
        sysUser.setDelFlag(sysUserDTO.getDelFlag());
        sysUser.setWorkNo(sysUserDTO.getWorkNo());
        sysUser.setPost(sysUserDTO.getPost());
        sysUser.setTelephone(sysUserDTO.getTelephone());
        sysUser.setCreateBy(sysUserDTO.getCreateBy());
        sysUser.setCreateTime(sysUserDTO.getCreateTime());
        sysUser.setUpdateBy(sysUserDTO.getUpdateBy());
        sysUser.setUpdateTime(sysUserDTO.getUpdateTime());
        sysUser.setActivitiSync(sysUserDTO.getActivitiSync());
        sysUser.setUserIdentity(sysUserDTO.getUserIdentity());
        sysUser.setDepartIds(sysUserDTO.getDepartIds());
        sysUser.setRelTenantIds(sysUserDTO.getRelTenantIds());
        sysUser.setClientId(sysUserDTO.getClientId());
        sysUser.setHomePath(sysUserDTO.getHomePath());
        sysUser.setPostText(sysUserDTO.getPostText());
        sysUser.setBpmStatus(sysUserDTO.getBpmStatus());
        return sysUser;
    }


    private SysUserDTO toSysUserDTO(SysUser sysUser) {
        if (sysUser == null) {
            return null;
        }
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setId(sysUser.getId());
        sysUserDTO.setUsername(sysUser.getUsername());
        sysUserDTO.setRealname(sysUser.getRealname());
        sysUserDTO.setPassword(sysUser.getPassword());
        sysUserDTO.setSalt(sysUser.getSalt());
        sysUserDTO.setAvatar(sysUser.getAvatar());
        sysUserDTO.setBirthday(sysUser.getBirthday());
        sysUserDTO.setSex(sysUser.getSex());
        sysUserDTO.setEmail(sysUser.getEmail());
        sysUserDTO.setPhone(sysUser.getPhone());
        sysUserDTO.setOrgCode(sysUser.getOrgCode());
        sysUserDTO.setLoginTenantId(sysUser.getLoginTenantId());
        sysUserDTO.setOrgCodeTxt(sysUser.getOrgCodeTxt());
        sysUserDTO.setStatus(sysUser.getStatus());
        sysUserDTO.setDelFlag(sysUser.getDelFlag());
        sysUserDTO.setWorkNo(sysUser.getWorkNo());
        sysUserDTO.setPost(sysUser.getPost());
        sysUserDTO.setTelephone(sysUser.getTelephone());
        sysUserDTO.setCreateBy(sysUser.getCreateBy());
        sysUserDTO.setCreateTime(sysUser.getCreateTime());
        sysUserDTO.setUpdateBy(sysUser.getUpdateBy());
        sysUserDTO.setUpdateTime(sysUser.getUpdateTime());
        sysUserDTO.setActivitiSync(sysUser.getActivitiSync());
        sysUserDTO.setUserIdentity(sysUser.getUserIdentity());
        sysUserDTO.setDepartIds(sysUser.getDepartIds());
        sysUserDTO.setRelTenantIds(sysUser.getRelTenantIds());
        sysUserDTO.setClientId(sysUser.getClientId());
        sysUserDTO.setHomePath(sysUser.getHomePath());
        sysUserDTO.setPostText(sysUser.getPostText());
        sysUserDTO.setBpmStatus(sysUser.getBpmStatus());
        return sysUserDTO;
    }


    private List<DepartIdModelDTO> toDepartIdModelDTOList(List<DepartIdModel> depIdModelList) {
        List<DepartIdModelDTO> departIdModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(depIdModelList)) {
            for (DepartIdModel departIdModel : depIdModelList) {
                departIdModelDTOList.add(toDepartIdModelDTO(departIdModel));
            }
        }
        return departIdModelDTOList;
    }

    private DepartIdModelDTO toDepartIdModelDTO(DepartIdModel departIdModel) {
        if (departIdModel == null) {
            return null;
        }
        DepartIdModelDTO departIdModelDTO = new DepartIdModelDTO();
        departIdModelDTO.setKey(departIdModel.getKey());
        departIdModelDTO.setValue(departIdModel.getValue());
        departIdModelDTO.setTitle(departIdModel.getTitle());
        //TODO 这里有递归逻辑，重点看下代码
        departIdModelDTO.setChildren(toDepartIdModelDTOList(departIdModel.getChildren()));
        return departIdModelDTO;
    }


    private List<SysUserDTO> toSysUserDTOList(List<SysUser> sysUsers) {
        List<SysUserDTO> sysUserDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sysUsers)) {
            for (SysUser sysUser : sysUsers) {
                sysUserDTOList.add(toSysUserDTO(sysUser));
            }
        }
        return sysUserDTOList;
    }


    private Page<SysUserDTO> toSysUserDTOPage(IPage<SysUser> pageList) {
        Page<SysUserDTO> sysUserDTOPage = new Page<>();
        List<SysUserDTO> sysUserDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysUser sysUser : pageList.getRecords()) {
                sysUserDTOList.add(toSysUserDTO(sysUser));
            }
        }

        sysUserDTOPage.setTotal(pageList.getTotal());
        sysUserDTOPage.setSize(pageList.getSize());
        sysUserDTOPage.setCurrent(pageList.getCurrent());
        sysUserDTOPage.setRecords(sysUserDTOList);
        return sysUserDTOPage;
    }


    private SysUserRoleVO toSysUserRoleVO(SysUserRoleVODTO sysUserRoleVODTO) {
        if (sysUserRoleVODTO == null) {
            return null;
        }
        SysUserRoleVO sysUserRoleVO = new SysUserRoleVO();
        sysUserRoleVO.setRoleId(sysUserRoleVODTO.getRoleId());
        sysUserRoleVO.setUserIdList(sysUserRoleVODTO.getUserIdList());
        return sysUserRoleVO;
    }


    private SysDepartUsersVO toSysDepartUsersVO(SysDepartUsersVODTO sysDepartUsersVODTO) {
        if (sysDepartUsersVODTO == null) {
            return null;
        }
        SysDepartUsersVO sysDepartUsersVO = new SysDepartUsersVO();
        sysDepartUsersVO.setDepId(sysDepartUsersVODTO.getDepId());
        sysDepartUsersVO.setUserIdList(sysDepartUsersVODTO.getUserIdList());
        return sysDepartUsersVO;
    }


    private SysUserAgent toSysUserAgent(SysUserAgentDTO sysUserAgentDTO) {
        if (sysUserAgentDTO == null) {
            return null;
        }
        SysUserAgent sysUserAgent = new SysUserAgent();
        sysUserAgent.setId(sysUserAgentDTO.getId());
        sysUserAgent.setUserName(sysUserAgentDTO.getUserName());
        sysUserAgent.setAgentUserName(sysUserAgentDTO.getAgentUserName());
        sysUserAgent.setStartTime(sysUserAgentDTO.getStartTime());
        sysUserAgent.setEndTime(sysUserAgentDTO.getEndTime());
        sysUserAgent.setStatus(sysUserAgentDTO.getStatus());
        sysUserAgent.setCreateName(sysUserAgentDTO.getCreateName());
        sysUserAgent.setCreateBy(sysUserAgentDTO.getCreateBy());
        sysUserAgent.setCreateTime(sysUserAgentDTO.getCreateTime());
        sysUserAgent.setUpdateName(sysUserAgentDTO.getUpdateName());
        sysUserAgent.setUpdateBy(sysUserAgentDTO.getUpdateBy());
        sysUserAgent.setUpdateTime(sysUserAgentDTO.getUpdateTime());
        sysUserAgent.setSysOrgCode(sysUserAgentDTO.getSysOrgCode());
        sysUserAgent.setSysCompanyCode(sysUserAgentDTO.getSysCompanyCode());
        return sysUserAgent;
    }


    private DepartAndUserInfoDTO toDepartAndUserInfoDTO(DepartAndUserInfo info) {
        if (info == null) {
            return null;
        }
        DepartAndUserInfoDTO departAndUserInfoDTO = new DepartAndUserInfoDTO();
        departAndUserInfoDTO.setUserList(toUserAvatarDTOList(info.getUserList()));
        departAndUserInfoDTO.setDepartList(toDepartInfoDTOList(info.getDepartList()));
        return departAndUserInfoDTO;
    }

    private List<DepartInfoDTO> toDepartInfoDTOList(List<DepartInfo> departList) {
        List<DepartInfoDTO> departInfoDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(departList)) {
            for (DepartInfo departInfo : departList) {
                departInfoDTOList.add(toDepartInfoDTO(departInfo));
            }
        }
        return departInfoDTOList;
    }

    private DepartInfoDTO toDepartInfoDTO(DepartInfo departInfo) {
        if (departInfo == null) {
            return null;
        }
        DepartInfoDTO departInfoDTO = new DepartInfoDTO();
        departInfoDTO.setId(departInfo.getId());
        departInfoDTO.setOrgName(departInfo.getOrgName());
        departInfoDTO.setOrgId(departInfo.getOrgId());
        return departInfoDTO;
    }

    private List<UserAvatarDTO> toUserAvatarDTOList(List<UserAvatar> userList) {
        List<UserAvatarDTO> userAvatarDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userList)) {
            for (UserAvatar userAvatar : userList) {
                userAvatarDTOList.add(toUserAvatarDTO(userAvatar));
            }
        }
        return userAvatarDTOList;
    }

    private UserAvatarDTO toUserAvatarDTO(UserAvatar userAvatar) {
        if (userAvatar == null) {
            return null;
        }
        UserAvatarDTO userAvatarDTO = new UserAvatarDTO();
        userAvatarDTO.setId(userAvatar.getId());
        userAvatarDTO.setRealname(userAvatar.getRealname());
        userAvatarDTO.setAvatar(userAvatar.getAvatar());
        return userAvatarDTO;
    }


    private UpdateDepartInfoDTO toUpdateDepartInfoDTO(UpdateDepartInfo info) {
        if (info == null) {
            return null;
        }
        UpdateDepartInfoDTO updateDepartInfoDTO = new UpdateDepartInfoDTO();
        updateDepartInfoDTO.setDepartId(info.getDepartId());
        updateDepartInfoDTO.setDepartName(info.getDepartName());
        updateDepartInfoDTO.setParentId(info.getParentId());
        updateDepartInfoDTO.setHasSub(info.getHasSub());
        updateDepartInfoDTO.setChargePersonList(info.getChargePersonList());
        return updateDepartInfoDTO;
    }


    private UpdateDepartInfo toUpdateDepartInfo(UpdateDepartInfoDTO updateDepartInfoDTO) {
        if (updateDepartInfoDTO == null) {
            return null;
        }
        UpdateDepartInfo updateDepartInfo = new UpdateDepartInfo();
        updateDepartInfo.setDepartId(updateDepartInfoDTO.getDepartId());
        updateDepartInfo.setDepartName(updateDepartInfoDTO.getDepartName());
        updateDepartInfo.setParentId(updateDepartInfoDTO.getParentId());
        updateDepartInfo.setHasSub(updateDepartInfoDTO.getHasSub());
        updateDepartInfo.setChargePersonList(updateDepartInfoDTO.getChargePersonList());
        return updateDepartInfo;
    }
}
